# -*- coding: utf-8 -*-
import hashlib
import json
import time
import urllib
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '88000006': {
        'API_KEY': 'FeI1kNMm50WuChxDvy3ifTRnJZQq29soljbgztcPdEBwUY7SAGX6VprLHaK84O',
        'gateway': 'http://www.oketernity.com/mctrpc/order/mkReceiptOrder.htm',
        'query_gateway': 'http://www.oketernity.com/mctrpc/order/queryOrderFromMerchant.htm',
    },
    '100001': {
        'API_KEY': '1234512345',
        'gateway': 'http://api.99epay.net/mctrpc/order/mkReceiptOrder.htm',
        'query_gateway': 'http://api.99epay.net/mctrpc/order/mkReceiptOrder.htm',
    },
    '90000015': {
        'API_KEY': 'q9j4o8zgr8kh7l4tfwtw0hledlcugfcqmy571m3h3010um0a749tf0w6ib6jr0afipkrmqqt',
        'gateway': 'http://119.28.34.43/mctrpc/order/mkReceiptOrder.htm',
        'query_gateway': 'http://119.28.34.43/mctrpc/order/mkReceiptOrder.htm',
    },
}


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _gen_sha256_sign(s):
    m = hashlib.sha256()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        s += str(parameter[k])
    s += key
    return _gen_sha256_sign(s)


def verify_notify_sign(j, sign, key):
    calculated_sign = _gen_sha256_sign(j + key)
    if sign != calculated_sign:
        _LOGGER.info("okpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % j)


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '210.5.58.146'


# 微信H5⽀付(WAP) 5_<⽀付⾦额> 5_10 ⽀付⾦额为10元
# QQ钱包扫码⽀付 9_<⽀付⾦额> 9_0.1 ⽀付⾦额为0.1元
# 京东扫码⽀付 10_<⽀付⾦额> 10_0.1 ⽀付⾦额为0.1元
# ⽀付宝扫码 ⽀付宝wap 12

def _get_pay_type(service):
    if service == 'wxpay':
        payType = '5'
    elif service == 'alipay':
        payType = '12'
    elif service == 'qq':
        payType = '9'
    elif service == 'jd':
        payType = '10'
    else:
        payType = '12'
    return payType


def _get_str(s, start, end):
    p1 = s.index(start)
    p2 = s.index(end, p1 + len(start))
    if p2 > p1:
        return s[p1 + len(start): p2]
    else:
        return ''


def get_phone_type(info):
    if 'android' in info['sdk_version'].lower():
        return 'AND_WAP'
    else:
        return 'iOS_WAP'


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('version', '1.1'),
        ('merchantId', app_id),
        ('merchantTime', time.strftime("%Y%m%d%H%M%S")),
        ('traceNO', str(pay.id)),
        ('requestAmount', int(pay_amount)),
        ('returnUrl', '{}/pay/api/{}/okpay/{}/'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id)),
        ('notifyUrl', '{}/pay/api/{}/okpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('goodsName', 'charge'),
        ('goodsCount', 1),
        ('ip', _get_device_ip(info)),
        ('paymentCount', '1'),
        ('payment_1', '%s_%s' % (_get_pay_type(service), int(pay_amount))),
    ))
    if service == 'wxpay':
        parameter_dict['extend'] = u'wap_url={}&wap_name={}&{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PREFIX,
                                                                       'charge')
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    _LOGGER.info("okpay create data : %s", parameter_dict)
    response = requests.post(_get_gateway(app_id), data=parameter_dict, headers=headers, timeout=10)
    _LOGGER.info("okpay create charge rsp data: %s %s", response.status_code, response.text)
    if service == 'wxpay':
        j_str = _get_str(response.text, '|', '|')
        j = json.loads(j_str)
        if 'IOS' in get_phone_type(info):
            url = j['payments'][0]['itemResponseMsg']['localUrl']
        else:
            url = j['payments'][0]['itemResponseMsg']['wxurl']
        _LOGGER.info("okpay create  rsp url: %s", url)
        return {'charge_info': url}
    else:
        return {'charge_info': _get_str(response.text, 'barcodeInfo":"', '"')}


def _get_return_code(s):
    return s[0:s.index('|')]


def _get_return_sign(s):
    t = s[s.index('|') + 1:]
    return t[t.index('|') + 1:]


def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    _LOGGER.info("okpay notify data: %s", request.body)
    request_body = str(urllib.unquote(request.body).decode('utf8'))
    _LOGGER.info("okpay notify request_body: %s", request_body)
    rcode = _get_return_code(request_body)
    r_sign = _get_return_sign(request_body)
    r_json = _get_str(request_body, '|', '|')
    verify_notify_sign(r_json, r_sign, api_key)
    j = json.loads(r_json)
    pay_id = j['traceNO']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % j)
        raise ParamError('okpay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(j['orderStatus'])
    trade_no = j['orderId']
    total_fee = float(j['orderSuccAmount'])

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == '1':
        _LOGGER.info('okpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    # prepare param
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('merchantId', app_id),
        ('traceNO', str(pay_id)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=parameter_dict, headers=headers, timeout=3)
    if response.status_code == 200:
        # response text is a pure html text
        j_str = _get_str(response.text, '|', '|')
        data = json.loads(j_str)
        trade_status = str(data['orderStatus'])
        trade_no = str(data['orderId'])
        total_fee = float(data['orderSuccAmount'])

        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        if trade_status == '1':
            _LOGGER.info('okpay query order success, user_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            res = order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                           total_fee, trade_no, extend)
            if res:
                # async notify
                async_job.notify_mch(pay_order.id)
            print("order process successfully. %s" % pay_order.id)
    else:
        _LOGGER.warn('okpay data error, status_code: %s', response.status_code)
